import { _decorator, Color, Component, Graphics, Node, RigidBody, RigidBody2D, Sprite, UITransform, v2, Vec2, Vec3 } from 'cc';
import { Collision } from './Collision';
import { CollisionManager } from './CollisionManager';
import { EventManager, MyEvent } from './EventManager';
const { ccclass, property } = _decorator;

@ccclass('CollisionItem')
export class CollisionItem extends Component {

    @property(Sprite)
    Icon: Sprite = null;

    @property
    MaxForce: number = 100;

    public RigidBody: RigidBody2D = null;
    public Collisions: Collision[] = [];
    public Color: Color = null;

    private _isPause: boolean = false;
    private _curLinearVelocity: Vec2 = new Vec2();

    protected start(): void {
        this.RigidBody = this.getComponent(RigidBody2D);
        // this.Color = this.getRandomBrightColor();
        this.Color = this.Icon.color;
        // this.applyRandomForce();
        CollisionManager.Instance.CollisionItems.push(this);
    }

    addCollision(collision: Collision) {
        this.Collisions.push(collision);
        collision.changeColor(this.Color);
    }

    removeCollision(collision: Collision) {
        const index: number = this.Collisions.findIndex(e => e == collision);
        if (index == -1) return;
        this.Collisions.splice(index, 1);
    }

    removeSelf() {
        this.Collisions.forEach(e => e.braak());
        this.Collisions = [];
        this.node.destroy();
    }

    //获取比较亮的颜色
    getRandomBrightColor(): Color {
        let r = Math.floor(128 + Math.random() * 128);
        let g = Math.floor(128 + Math.random() * 128);
        let b = Math.floor(128 + Math.random() * 128);
        return new Color(r, g, b, 255);
    }

    applyRandomForce() {
        if (!this.RigidBody) return;

        // 生成一个随机方向的单位向量
        let angle = Math.random() * Math.PI;
        let forceMagnitude = this.MaxForce;

        let forceX = Math.cos(angle) * forceMagnitude;
        let forceY = Math.sin(angle) * forceMagnitude; 66

        let force = v2(forceX, forceY);

        // 施加力，点是刚体的中心点(默认)
        const point: Vec2 = new Vec2();
        this.RigidBody.getWorldCenter(point);
        this.RigidBody.applyForce(force, point, true);

        // 如果想用冲量，可以用applyImpulse：
        // this.rigidBody.applyImpulse(force, this.rigidBody.getWorldCenter(), true);
    }

    private pause() {
        this._isPause = !this._isPause;
        if (this._isPause) {
            this._curLinearVelocity = this.RigidBody.linearVelocity;
            this.RigidBody.linearVelocity = Vec2.ZERO;
            this.RigidBody.gravityScale = 0;
        } else {
            this.RigidBody.gravityScale = 2;
            this.RigidBody.linearVelocity = this._curLinearVelocity;
        }
    }

    protected onEnable(): void {
        EventManager.on(MyEvent.PAUSE, this.pause, this);
    }

    protected onDisable(): void {
        EventManager.off(MyEvent.PAUSE, this.pause, this);
    }

}


